package com.ht.web360.base.utils;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * 基于Redis生成基于时间的顺序ID
 */
@Component
public class RedisIdWorker {

    /**
     * 开始时间戳
     */
    private static final long BEGIN_TIMESTAMP = 1640995200L;

    /**
     * 序列号位数
     */
    private static final int COUNT_BITS = 32;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public long nextId() {
        String prefix = "uuid:web360:";
        // 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowSecond - BEGIN_TIMESTAMP;
        // 生成序列号
        String today = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String key = prefix + today;
        Long countBox = stringRedisTemplate.opsForValue().increment(key);
        // 设置字段过期时间
        Long tempExpire = stringRedisTemplate.getExpire(key);
        if (tempExpire == null || tempExpire == -1) {
            stringRedisTemplate.expire(key, 3, TimeUnit.DAYS);
        }
        long count = countBox == null ? 0L : countBox;
        // 拼接并返回
        // 左移来让低位空出位置，然后用低位的0或上count来实现将count拼接在时间戳的低位的效果
        return timeStamp << COUNT_BITS | count;
    }
}